/**
 * Author:   YASUO
 * Date:     2018/6/19 17:29
 * Description:
 */
package com.rljk.controller.app;

import com.cxytiandi.encrypt.anno.Decrypt;
import com.cxytiandi.encrypt.util.AesEncryptUtils;
import com.rljk.common.controller.BaseController;
import com.rljk.common.result.CodeMsg;
import com.rljk.common.result.Result;
import com.rljk.domain.common.PageData;
import com.rljk.domain.vo.DecryptVo;
import com.rljk.redis.RedisService;
import com.rljk.service.CaidanManager;
import com.rljk.service.DotAgreeManager;
import com.rljk.service.HeadlinesManager;
import com.rljk.service.NewsDetailManager;
import com.rljk.service.impl.BroadcastImgService;
import com.rljk.service.impl.ProjectLibraryService;
import com.rljk.service.impl.VedioDetailService;
import com.rljk.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by YASUO on 2018/6/19.
 */
@RestController
@RequestMapping("/home")
@Slf4j
public class HomeInController extends BaseController{

    @Autowired
    RedisService redisService;

    @Resource(name = "caidanService")
    private CaidanManager caidanService;

    @Resource(name = "headlinesService")
    private HeadlinesManager headlinesService;

    @Resource(name = "newsdetailService")
    private NewsDetailManager newsDetailService;

    @Resource(name = "broadcastimgService")
    private BroadcastImgService broadcastImgService;

    @Resource(name = "dotAgreeService")
    private DotAgreeManager dotAgreeService;

    @Resource(name = "projectlibraryService")
    private ProjectLibraryService libraryService;

    @Resource(name = "vediodetailService")
    private VedioDetailService vedioDetailService;


//    /**
//     * 首页显示接口
//     * @Description
//     * @Author zhaozhenhua
//     * @date   2018年5月31日
//     * @return
//     * @throws Exception
//     */
//
//    @RequestMapping(value="/showview")
//    //@Encrypt
//    public Object showView() {
//        log.info("首页显示接口");
//        PageData pd = new PageData();
//        pd = this.getPageData();
//        log.info("请求参数："+pd.toString());
//        Map<String,Object> map = new HashMap<>();
//        try {
//            if (Tools.checkKey("SHOWVIEW", pd.getString("FKEY"))) {
//                pd.put("CAIDAN_TYPE","1");//1-代表首页菜单，2代表任务页面菜单
//                List<PageData> caidan = caidanService.listAll(pd);
//                if(Tools.isEmpty(pd.getString("CAIDAN_ID"))){
//                    log.debug("为空。。。。。。。。。。。。");
//                    pd.put("CAIDAN_ID","459765959234682893");
//                }
//                List<PageData> list = headlinesService.getByCaidanId(pd);
//                //默认进入快讯
//                map.put("caidan",caidan);
//                map.put("list",list);
//                return Result.success(map);
//            } else {
//                return Result.error(CodeMsg.FKEY_FAIL);
//            }
//        } catch (Exception e) {
//            log.error(e.toString(), e);
//            return Result.error(CodeMsg.SERVER_ERROR);
//        }
//    }


    /**
     * 首页显示接口-快讯，币圈，社区，观点派
     * @Description
     * @Author zhaozhenhua
     * @date   2018年5月31日
     * @return
     * @throws Exception
     */

    @RequestMapping(value="/showview")
    //@Encrypt
    public Object showView() {
        log.info("首页显示接口-快讯，币圈，社区，观点派");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("SHOWVIEW", pd.getString("FKEY"))) {
//                if (AppUtil.checkParam("showView",pd)){

                    //1.获取用户信息
                    if(Tools.notEmpty(pd.getString("TOKEN"))){
                        String USER_ID = redisService.get(pd.getString("TOKEN"));
                        pd.put("USER_ID",USER_ID);
                    }

                    List<PageData> list = headlinesService.getByCaidanId(pd);
                    if(Tools.isEmptyList(list)){
                        return Result.error(CodeMsg.EMPTY);
                    }

                    for (PageData ls:list) {
                        pd.put("HEADLINES_ID",ls.get("HEADLINES_ID"));

                        PageData dotAgreeMy = dotAgreeService.getDotAgreeMy(pd);

                        if (dotAgreeMy != null){
                            //1代表已点赞
                            ls.put("STATUS",1);
                        }else {
                            //0代表未点赞
                            ls.put("STATUS",0);
                        }

                    }
                    return Result.success(list);
//                }else {
//                    return Result.error(CodeMsg.PARAM_LACK);
//                }
			} else {
				return Result.error(CodeMsg.FKEY_FAIL);
			}
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * 首页显示接口-学院
     * @Description
     * @Author zhaozhenhua
     * @date   2018年5月31日
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/showviewcollege")
    public Object showViewCollege() {
        log.info("首页显示接口-社区，观点派");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("SHOWVIEWCOMMU", pd.getString("FKEY"))) {
//                if (AppUtil.checkParam("showView",pd)){

                //1.获取用户信息
                if(Tools.notEmpty(pd.getString("TOKEN"))){
                    String USER_ID = redisService.get(pd.getString("TOKEN"));
                    pd.put("USER_ID",USER_ID);
                }

                List<PageData> list = headlinesService.getCollegeById("21000");
                if(Tools.isEmptyList(list)){
                    return Result.error(CodeMsg.EMPTY);
                }

                for (PageData p : list) {
                    p.put("CREATE_TIME",RelativeDateFormat.format(p.getString("CREATE_TIME")));
                }

                for (PageData ls:list) {
                    pd.put("HEADLINES_ID",ls.get("HEADLINES_ID"));

                    PageData dotAgreeMy = dotAgreeService.getDotAgreeMy(pd);

                    if (dotAgreeMy != null){
                        //1代表已点赞
                        ls.put("STATUS",1);
                    }else {
                        //0代表未点赞
                        ls.put("STATUS",0);
                    }

                }
                return Result.success(list);
//                }else {
//                    return Result.error(CodeMsg.PARAM_LACK);
//                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }



    /**
     * 获取首页菜单
     * @Description
     * @Author zhaozhenhua
     * @date   2018年8月23日
     * @return
     * @throws Exception
     */

    @RequestMapping(value="/showviewcaidan")
    public Object showViewCaiDan() {
        log.info("获取首页菜单");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("SHOWVIEWCAI", pd.getString("FKEY"))) {
//                if (AppUtil.checkParam("showView",pd)){
                pd.put("CAIDAN_TYPE","1");//1-代表首页菜单，2代表任务页面菜单
                List<PageData> caidan = caidanService.listAll(pd);
                for (PageData p : caidan) {
                    p.remove("CAIDAN_TYPE");
                    p.remove("SEQUENCE");
                }
                for (PageData p : caidan) {
                    PageData p1= new PageData();
                    p1.put("CAIDAN_TYPE",p.getString("CAIDAN_ID"));
                    List<PageData> sonCaiDan = caidanService.listAll(p1);
                    if(Tools.notEmptyList(sonCaiDan)){
                        for (PageData p2 : sonCaiDan) {
                            p2.remove("CAIDAN_TYPE");
                            p2.remove("SEQUENCE");
                        }
                        p.put("sonCaiDan",sonCaiDan);
                    }/*else {
                        p.put("sonCaiDan",sonCaiDan);
                    }*/
                }
                return Result.success(caidan);
//                }else {
//                    return Result.error(CodeMsg.PARAM_LACK);
//                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }




    /**
     * 获取新闻详情
     * @Description
     * @Author zhaozhenhua
     * @date   2018年7月7日
     */
    @RequestMapping(value="/newsdetail")
    //@Encrypt
    public Object getNewsDetail() {
        log.info("获取新闻详情");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("NEWSDETAIL", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("getNewsDetail",pd)){
                    PageData newsDetail = newsDetailService.getNewsDetailById(pd);
                    if(newsDetail!=null){
                        map.put("newsDetail",newsDetail);
                        return Result.success(map);
                    }else {
                        return Result.error(CodeMsg.EMPTY);
                    }
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * 获取学院详情
     * @Description
     * @Author zhaozhenhua
     * @date   2018年8月23日
     */
    @RequestMapping(value="/collegedetail")
    //@Encrypt
    public Object getCollegeDetail() {
        log.info("获取学院详情");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object>map = new HashMap<>();
        try {
            if (Tools.checkKey("COLLEGEDETAIL", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("getNewsDetail",pd)){
                    PageData newsDetail = newsDetailService.getNewsDetailById(pd);
                    newsDetail.remove("SMALL_PORTRAIT");
                    if(newsDetail!=null){
                        newsDetail.put("PUBLISH_TIME", RelativeDateFormat.format(newsDetail.getString("PUBLISH_TIME")));
                        newsDetail.put("IS_FOLLOW", 0);
                        map.put("newsDetail",newsDetail);
                        List<PageData> vedioList = vedioDetailService.getVideoListById(newsDetail.getString("NEWSDETAIL_ID"));
                        map.put("选集",vedioList);
                        return Result.success(map);
                    }else {
                        return Result.error(CodeMsg.EMPTY);
                    }
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }

    /**
     * app根据导航栏显示轮播图
     * @Description
     * @Author zhaozhenhua
     * @date   2018年7月9日
     */
    @RequestMapping(value="/broadcast")
    //@Encrypt
    public Object getBroadCast() {
        log.info("app根据导航栏显示轮播图");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("BROADCAST", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("getBroadCast",pd)){
                    List<String> list = new ArrayList<>();
                    List<PageData> broadList = broadcastImgService.getBroadCast(pd);
                    if(Tools.isEmptyList(broadList)){
                        return Result.error(CodeMsg.EMPTY);
                    }
                    for (PageData p : broadList) {
                        list.add(p.getString("SHOWIMAGE"));
                    }
                    map.put("list",list);
                    return Result.success(map);
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * @Author zhang
     * @Description  app是否点赞
     * @Date 2018/8/6 11:57
     * @Param []
     * @return java.lang.Object
     **/
    @RequestMapping(value="/isDotAgree")
    public Object getIsDotAgree() {
        log.info("app是否点赞功能");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("ISDOTAGREE", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("getIsDotAgree",pd)){
                    //1.获取用户信息
                    String USER_ID = redisService.get(pd.getString("TOKEN"));
                    pd.put("USER_ID",USER_ID);
                    PageData dotAgreeMy = dotAgreeService.getDotAgreeMy(pd);

                    return Result.success(dotAgreeMy);
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * @Author zhang
     * @Description  app点赞功能
     * @Date 2018/8/6 11:35
     * @Param []
     * @return java.lang.Object
     **/
        @RequestMapping(value="/getDotAgree")
    public Object getDotAgree() {
        log.info("app点赞功能");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("DOTAGREE", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("getDotAgree",pd)){
                    //1.获取用户信息
                    String USER_ID = redisService.get(pd.getString("TOKEN"));

                    pd.put("USER_ID",USER_ID);

                    //2.获取点赞状态
                    String status = (String) pd.get("STATUS");

                    //3.查询点赞数量
                    PageData headlinesServiceById = headlinesService.findById(pd);

                    Integer concernNum = (Integer)headlinesServiceById.get("CONCERN_NUM");


                    if (StringUtils.equals(status,"1")){
                        pd.put("DOTAGREE_ID",this.getSnowId());


                        dotAgreeService.save(pd);
                        //点赞则关注数加1
                        concernNum = concernNum + 1;

                        pd.put("CONCERN_NUM",concernNum);

                    }else if (StringUtils.equals(status,"0")){
                        dotAgreeService.delete(pd);

                        //取消点赞则关注数减1
                        concernNum = concernNum - 1;

                        pd.put("CONCERN_NUM",concernNum);
                    }
                    //修改点赞数量
                    headlinesService.edit(pd);

                    map.put("CONCERN_NUM",concernNum);

                    return Result.success(map);
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * @Author zhang
     * @Description 通过用户ID统计有哪些人点赞过该用户的文章
     * @Date 2018/8/27 10:07
     * @Param []
     * @return java.lang.Object
     **/
    @RequestMapping(value="/userdotAgreelist")
    public Object getDotAgreeByUserID() {
        log.info("通过用户ID统计有哪些人点赞过该用户的文章");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("GETDOTAGREEBYUSERID", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("getDotAgreeByUserID",pd)){
                    //1.获取用户信息
                    String USER_ID = redisService.get(pd.getString("TOKEN"));
                    pd.put("USER_ID",USER_ID);
                    List<PageData> dotAgreeByUserID = dotAgreeService.getDotAgreeByUserID(pd);

                    if (dotAgreeByUserID.size() != 0){
                        for (PageData pageData : dotAgreeByUserID){
                            String agreetime = (String)pageData.get("AGREETIME");
                            String format = RelativeDateFormat.format(agreetime);
                            pageData.put("AGREETIME",format);
                            pageData.put("DESCRIBE","赞了您的作品《" + pageData.get("TITLE") + "》");
                            pageData.remove("TITLE");
                        }

                        return Result.success(dotAgreeByUserID);
                    }else {
                        return Result.success(dotAgreeByUserID);
                    }

                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * @Author zhang
     * @Description  APP转发数量
     * @Date 2018/8/6 17:26
     * @Param []
     * @return java.lang.Object
     **/
    @RequestMapping(value="/forwardNum")
    public Object getForward() {
        log.info("app转发数量");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        Map<String,Object> map = new HashMap<>();
        try {
            if (Tools.checkKey("GETFORWARD", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("getForward",pd)){
                    PageData info = headlinesService.findById(pd);
                    Integer forwardNum = (Integer)info.get("FORWARD_NUM");
                    forwardNum = forwardNum + 1;
                    pd.put("FORWARD_NUM",forwardNum);

                    headlinesService.edit(pd);
                    
                    map.put("FORWARD_NUM",forwardNum);
                    return Result.success(map);
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }

    /**
     *  app获取项目库
     * @return
     */
    @RequestMapping(value="/getprojectlibrary")
    public Object getProjectLibrary() {
        log.info("app获取项目库");
        PageData pd = new PageData();
        pd = this.getPageData();
        log.info("请求参数："+pd.toString());
        List<Object> project =new ArrayList<>();
        try {
            if (Tools.checkKey("PROLIBRARY", pd.getString("FKEY"))) {
                if (AppUtil.checkParam("useridParam",pd)){
                    Map<String,Object> hotMap = new HashMap<>();
                    List<PageData> hotLibrary = libraryService.getHotLibrary("1");

                    hotMap.put("name","热门项目");
                    hotMap.put("list",hotLibrary);
                    project.add(hotMap);

                    Map<String,Object> allMap = new HashMap<>();
                    List<Object> list = new ArrayList<>();
                    String str= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    List<PageData> sortLibrary = null;
                    for(int i=0;i<str.length();i++){
                        Map<String,Object> map1 = new HashMap<>();
                        char c = str.charAt(i);
                        sortLibrary = libraryService.getSortLibrary(String.valueOf(c));
                        if(Tools.notEmptyList(sortLibrary)){
                            map1.put("letter",String.valueOf(c));
                            map1.put("sortLibrary",sortLibrary);
                            list.add(map1);
                        }
                    }
                    allMap.put("name","全部项目");
                    allMap.put("list",list);
                    project.add(allMap);
                    return Result.success(project);
                }else {
                    return Result.error(CodeMsg.PARAM_LACK);
                }
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    /**
     * 首页发布
     * @param mreq
     * @param resp
     * @param request
     * @param TITLE
     * @param CONTENT
     * @param CAIDAN_ID
     * @param TOKEN
     * @param fileName
     * @return
     */
    @RequestMapping(value="/homepublish")
    @ResponseBody
    public Object homePublish(MultipartHttpServletRequest mreq, HttpServletResponse resp, HttpServletRequest request, String TITLE,
                                            String  CONTENT, String  CAIDAN_ID,String TOKEN){
        log.info("首页发布");
        PageData pd = new PageData();
        pd = this.getPageData();
        String SHOWIMAGE="";
        try {
            if (Tools.checkKey("HOMEPUBLISH", pd.getString("FKEY"))) {    //检验请求key值是否合法
                //if(AppUtil.checkParam("addApplyBusiness", pd)){	//检查参数
                Object USER_ID = redisService.getUserIdByToken(TOKEN);
                pd.put("TITLE", TITLE);
                pd.put("CONTENT", CONTENT);
                pd.put("CAIDAN_ID", CAIDAN_ID);
                pd.put("AUTHOR_ID", USER_ID);
                pd.put("HEADLINES_ID", SnowIdUtil.getSnowId());
                pd.put("NEWSDETAIL_ID", SnowIdUtil.getSnowId());
                if (mreq.getFile("files").isEmpty()) {
                } else {
                    SHOWIMAGE = FTPUtils.upMultiImgs(mreq, resp, "files", "gemstone/test");
                }
                pd.put("SHOWIMAGE", SHOWIMAGE);
                headlinesService.save(pd);
                pd.put("PUBLISH_TIME", DateUtil.getTime());
                pd.put("HEAD_PORTRAIT", "http://image.rongyaohk.com/gemstone/portrait/news_image_head@2x.png");
                newsDetailService.save(pd);
                return Result.success();
           /* }else {
                return Result.error(CodeMsg.PARAM_LACK);
            }*/
            } else {
                return Result.error(CodeMsg.FKEY_FAIL);
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }


    @RequestMapping(value="/decrypt")
    @Decrypt
    public Object destest()  {
        log.info("测试解密");
        PageData pd = new PageData();
        pd = this.getPageData();
        Map<String,Object> map = new HashMap<>();
        try {
            String s = AesEncryptUtils.aesDecrypt(pd.getString("param"), "d7b85f6e214abcda");
            System.out.println("解密数据：{}"+s);
          return Result.success(s);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }

    @PostMapping(value="/decrypt1")
    @Decrypt
    public Object destest1(@RequestBody DecryptVo decryptVo){
        log.info("测试解密1");
        System.out.println("解密数据：{}"+decryptVo);
        try {
            return Result.success(decryptVo);
        } catch (Exception e) {
            log.error(e.toString(), e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
